package test.concurrent;

/**
 * 模仿CAS
 *
 * @author yachao.guo
 * @date 2019-07-02 17:12
 */
public class SimulateCAS {

    volatile int count;
    int addOne() {
        int oldValue;
        int newValue;
        do {
            oldValue = count;
            newValue = count + 1;
        } while (oldValue!=cas(oldValue,newValue));
        return newValue;
    }

    synchronized int cas(int expect,int newValue){
        int curValue = count;
        if(curValue == expect){
            count = newValue;
        }
        return curValue;
    }
}
